package com.atguigu.gmall.weball.controller;


import com.atguigu.gmall.common.result.Result;
import com.atguigu.gmall.common.util.AuthContextHolder;
import com.atguigu.gmall.feign.order.OrderFeignClient;
import com.atguigu.gmall.feign.pay.PayFeignClient;
import com.atguigu.gmall.model.order.OrderInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.Map;

@Controller
public class PayController {


    @Autowired
    OrderFeignClient orderFeignClient;

    @Autowired
    PayFeignClient payFeignClient;

    @GetMapping("/pay.html")
    public String payPage(@RequestParam("orderId") Long orderId,
                          Model model){


        //1、订单信息 orderInfo:
        Result<OrderInfo> result = orderFeignClient.getOrderInfo(orderId);
        if(result.isOk()){
            model.addAttribute("orderInfo",result.getData());
        }

        return "payment/pay";
    }


    @RequestMapping("/pay/success")
    public String paySuccess(@RequestParam Map<String,String> params){

        System.out.println(params);
        //订单状态如果在这里修改？风险。
        String out_trade_no = params.get("out_trade_no");
        Long userId = AuthContextHolder.getUserIdBo().getUserId();

        //1、验证签名
        Result result = payFeignClient.checkSign(params);
        if(result.isOk()){
            //验签通过，这就是支付宝的响应
            System.out.println("验签通过，这就是支付宝的响应");
            //修改此订单状态为已支付。远程调用改订单状态；订单改状态用异步通知
            //远程调用不是很可靠，我们需要订单的状态一定能保证修改了；
            //orderFeignClient.updateOrderStatus(userId,out_trade_no, OrderStatus.PAID.name(), ProcessStatus.PAID.name());
        }else {
            //伪造响应
            System.out.println("伪造响应");

        }
        return "payment/success";
    }

}
